package com.guchenbo.example.k8s;

import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;

import java.io.IOException;

public class ClientDemo {
    public static String masterUrl = "https://10.57.27.108:6443";
    public static String token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IkpmVTJfcFk2OVR1Y1Z4am1SQlg3X0lMU2lQT21LZUN0SEpPbTVDalA5ZmsifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJkYXNoYm9hcmQtYWRtaW4tc2VjcmV0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImRhc2hib2FyZC1hZG1pbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjFhZTBlODY3LWI0NDUtNGZlNS05MmNhLTlkZjIzNWIzMGYyNiIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDprdWJlcm5ldGVzLWRhc2hib2FyZDpkYXNoYm9hcmQtYWRtaW4ifQ.NrtEaDNOD2dgKltol0EULeaq8GQ2gvAYPu7chfOytthgG7Wyc6jLVK6VngoR2X-xNVzAfgHodMjr2LZeFf3sWUoKjK7PNLeyINRVzmqQDpsxmLiueUUHjb-v4Hi4lG1IfbAptdNjUYOKimpiGneu00EsCZhAvhOUTxOFGHJAESPpQLixKJ8imrvZElUaqnHVp2puuw2WnDtXX4kHyGKgIAjKGCsANvxR3j237CjSOzWilX0KPOZwV75XSmIUqQ8sorZ9k40iKH4RpLJjvDANt5gv_iGTSgJPlQE0ogY56DrjF5LCCnIkMc7-hUVkGD71vfJ6DOokUrzLlfPv0OuU1w";
    public static String namespace = "default";

    private KubernetesClient client;

    public ClientDemo() {
        Config config = new ConfigBuilder().withMasterUrl(masterUrl).withOauthToken(token).build();
        client = new KubernetesClientBuilder().withConfig(config).build();
    }

    public String create() {
        String realImage = "magickube.hub:5000/mingmo/nginx:1.18.0-arm";
        Deployment deployment = client.apps().deployments()
                        .load(ClientDemo.class.getResourceAsStream("/k8s/deployment.yaml")).item();
        deployment.getSpec().getTemplate().getSpec().getContainers().get(0).setImage(realImage);

        deployment = client.resource(deployment).inNamespace(namespace).serverSideApply();
        System.out.println(deployment.getStatus());

        return deployment.getMetadata().getName();
    }

    private void delete(String name) {
        client.apps().deployments().inNamespace(namespace).withName(name).delete();
    }

    public static void main(String[] args) throws IOException {
        ClientDemo clientDemo = new ClientDemo();

        // 1、create deployment
        clientDemo.create();

        // delete
//        clientDemo.delete("nginx");

    }
}
